<!-- 能耗分析页面 -->

<script setup lang="ts">
import { ref, onMounted, watch, toRef, toRefs, onBeforeMount } from "vue";
import * as echarts from "echarts"; //引入echarts核心模块
import axios from "axios"; //引入echarts核心模块
import { Search } from "@element-plus/icons-vue";
// import Index from "./views/index/index.vue";

const value2 = ref([]);

const shortcuts = [
  {
    text: "上一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    },
  },
  {
    text: "上一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  },
  {
    text: "前三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);
      return [start, end];
    },
  },
];
const chart = ref(); //创建dom引用

const xAxis_data = ref();
const series_data = ref();
const warningLines = {
  BB7: 61.1,
  BB2: 454,
  BB1: 369.9,
  BB3: 376.6,
  BB4: 375.5,
  BB5: 368.3,
  // ...其他区域和它们对应的警戒线值
} as const;
const warningLines1 = {
  BB7: 9.5,
  BB2: 9.7,
  BB1: 5.2,
  BB3: 10.7,
  BB4: 10.5,
  BB5: 27.2,
  // ...其他区域和它们对应的警戒线值
} as const;
const determineColor = (value: string, dataValue: number) => {
  if (value === "BB5") {
    return dataValue > 60 ? "lightblue" : "#00ff00";
  } else {
    // 新增逻辑：对于其他模块，判断是否大于30
    return dataValue > 25 ? "lightblue" : "#00ff00";
  }
};

const initChart = () => {
  if (chart.value == null) {
    return;
  }
  echarts.dispose(chart.value);
  var myChart = echarts.init(chart.value);
  myChart.setOption({});
  var option = {
    tooltip: {
      // 触发类型，默认数据触发，可选为：'item' | 'axis'
      trigger: "axis",
      // formatter: function (data: any) {
      //   return "小时能耗" + data.value;
      // },
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ["line", "bar"] },
        restore: { show: true },
        saveAsImage: { show: true },
      },
    },

    title: {
      text: "能耗分析统计",
      left: "center",
      textStyle: {
        color: "white", // 设置标题颜色为白色
      },
      subtext: "单位：KWh",
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: xAxis_data.value,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "实际能耗",
        data: series_data.value,
        type: "bar",
        label: {
          show: true,
          position: "top",
          formatter: function (data: any) {
            return data.value;
          },
          color: "#fff", // 文字颜色
          fontSize: 12, // 文字大小
        },
        itemStyle: {
          // 使用定义好的函数来动态设置颜色
          color: function (params: any) {
            return determineColor(value3.value, params.data);
          },
        },
        markLine: {
          data: [
            // 设置具体数值的监控线,第一条监控线
            {
              type: "average",
              name: "平均值",
              lineStyle: { type: "solid", color: "red" },
              label: { show: true, position: "middle" },
              // tooltip: {
              //   show: true, // 显示提示框
              //   formatter: "这是一个监控线的提示：{c}", // 自定义提示框内容
              // },
            },

            // 设置超过最大值的部分颜色
            {
              yAxis: warningLines[value3.value] || 90,
              name: "警戒线",
              lineStyle: { type: "dashed" },
              label: { show: true },
            },
            {
              yAxis: warningLines1[value3.value] || 90,
              name: "警戒线",
              lineStyle: { type: "dashed" },
              label: { show: true },
            },
          ],
        },
      },
    ],
    dataZoom: [
      {
        // 这是一个垂直（纵向）的滑动条
        type: "slider", // 组件类型为滑动条
        start: 0, // 默认数据初始位置（百分比）
        end: 100, // 默认数据结束位置（百分比）
      },
      {
        // 这是一个水平（横向）的缩放控制
        type: "inside", // 组件类型为内置缩放
        start: 90, // 默认数据初始位置（百分比）
        end: 100, // 默认数据结束位置（百分比）
      },
    ],
  };

  myChart.setOption(option);
};
var start_time_temp: any;
var end_time_temp: any;
var item_temp: any;
var page_size_temp: any;
// 在组件挂载后显示最近7天的装配能耗数据
onMounted(() => {
  axios.get("http://10.64.35.32:8000/energy_analysis/get_energy_data/" + "?start_time=" + start_time_temp + "&end_time=" + end_time_temp + "&item=" + item_temp + "&page_size=" + page_size_temp).then((res) => {
    console.log(res);
    console.log("请求到数据啦");
    processed_Array.value = processArray(res.data);
    console.log(processed_Array.value);
    // 将proxy对象转成 普通数组
    const normalArr = processed_Array.value.map((proxyObj: any) => {
      return { ...proxyObj };
    });
    console.log(normalArr);
    const normalArr_delete = normalArr.shift();
    console.log(normalArr_delete);

    xAxis_data.value = normalArr.map((item: any) => item.time);
    series_data.value = normalArr.map((item: any) => item.val);

    console.log(xAxis_data.value);
    console.log(series_data.value);

    initChart();
  });
});

onBeforeMount(() => {
  console.log("这是组件挂载前显示的内容函数");

  // 设置7天前的时间
  const daysBefore = 7;
  // 获取当前日期时间
  const now_1 = new Date();
  // 将当前日期时间转换为字符串，格式类型为中国标准时间字符串
  const now = now_1.toString();
  // 获取daysBefore天前的日期时间，格式类型为时间戳number
  const now_minus_seven = now_1.setDate(now_1.getDate() - daysBefore);
  console.log(now);
  // 将时间戳转换为日期时间格式yyyy-mm-dd hh:mm:ss
  const now_minus_seven2 = timestampToDateFormat1(now_minus_seven);
  console.log(now_minus_seven2);
  console.log(typeof now_minus_seven2);
  const now_string = formatDate(now);
  console.log(now_string);
  start_time_temp = now_minus_seven2;
  end_time_temp = now_string;
  item_temp = "BB7";
  page_size_temp = 100;
});

function processArray(arr: { val: number }[]): { val: number }[] {
  for (let i = arr.length - 1; i > 0; i--) {
    const currentVal = arr[i].val;
    const previousVal = arr[i - 1].val;
    arr[i].val = currentVal - previousVal;
  }
  return arr;
}

// const print_value2 = () => {
//   console.log("定时器触发");
//   console.log(value2.value);
//   console.log(value2.value[0]);
//   console.log(typeof value2.value[0]);
//   console.log(value2.value[1]);
// };
const value3 = ref("");
const value4 = ref("");
const options = [
  {
    value: "BB7",
    label: "装配",
  },
  {
    value: "BB1",
    label: "缸盖1",
  },
  {
    value: "BB2",
    label: "缸盖2",
  },
  {
    value: "BB3",
    label: "缸体1",
  },
  {
    value: "BB4",
    label: "缸体2",
  },
  {
    value: "BB5",
    label: "曲轴",
  },
];
const options2 = [
  {
    value: 25,
    label: "1天",
  },
  {
    value: 49,
    label: "2天",
  },
  {
    value: 73,
    label: "3天",
  },
  {
    value: 97,
    label: "4天",
  },
  {
    value: 121,
    label: "5天",
  },
  {
    value: 241,
    label: "10天",
  },
];
// setTimeout(function () {
//   setInterval(print_value2, 5000);
// }, 5000);

// 中国标准时间字符串转换为YY-MM-DD HH:MM:SS格式
function formatDate(d: string) {
  var date = new Date(d);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
}
// 时间戳字符串转换为YY-MM-DD HH:MM:SS格式
function timestampToDateFormat1(timestamp: any) {
  var date = new Date(timestamp);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

  return YY + MM + DD + " " + hh + mm + ss;
}
const processed_Array = ref();
//根据时间范围获取对应的数据
const show_data_in_html = (url: string) => {
  //发起后端请求
  axios.get(url).then((res) => {
    console.log(res);
    console.log(res.data);

    processed_Array.value = processArray(res.data);
    console.log(processed_Array.value);
    // 将proxy对象转成 普通数组
    const normalArr = processed_Array.value.map((proxyObj: any) => {
      return { ...proxyObj };
    });
    console.log(normalArr);
    const normalArr_delete = normalArr.shift();
    console.log(normalArr_delete);

    xAxis_data.value = normalArr.map((item: any) => item.time);
    series_data.value = normalArr.map((item: any) => item.val);

    console.log(xAxis_data.value);
    console.log(series_data.value);

    initChart();
  });
};

//对数组进行处理
// const get_need_name_arry = (objectsList: { time: string; item: string; name: string }[]) => {
//   objectsList.map((obj) => obj.name);
// };
// const get_need_time_arry = (objectsList: { time: string; item: string; name: string }[]) => {
//   objectsList.map((obj) => obj.time);
// };
//调用函数
var construct_url = "";
watch([value2, value3, value4], () => {
  console.log(value2.value[0]);
  const start_time: Object = formatDate(value2.value[0]);
  const end_time: Object = formatDate(value2.value[1]);
  console.log(start_time);
  console.log(typeof start_time);
  console.log(end_time);
  construct_url = "http://10.64.35.32:8000/energy_analysis/get_energy_data" + "?start_time=" + start_time?.toString() + "&end_time=" + end_time?.toString() + "&item=" + value3.value + "&page_size=" + value4.value;
});

const use_show_data_in_html = () => {
  console.log(construct_url);
  show_data_in_html(construct_url);
};
</script>
<template>
  <h3 style="display: flex">能耗分析模块:</h3>
  <el-row>
    <div class="block">
      <el-date-picker v-model="value2" type="datetimerange" :shortcuts="shortcuts" range-separator="To" start-placeholder="起始日期" end-placeholder="结束日期" />
    </div>
    <div class="block">
      <el-select v-model="value3" placeholder="选择区域" style="width: 240px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>
    <div class="block">
      <el-select v-model="value4" placeholder="选择显示天数" style="width: 140px">
        <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>

    <div class="block">
      <el-button type="primary" :icon="Search" @click="use_show_data_in_html">查询</el-button>
    </div>
  </el-row>
  <div>
    <div ref="chart" style="height: 500px; width: 1300px"></div>
  </div>
</template>

<style scoped>
h3 {
  color: rgb(0, 0, 0);
}

.block {
  padding: 20px;
  text-align: center;
  /* border-right: solid 1px var(--el-border-color); */
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
